# -*- coding: utf-8 -*-
import sys
from threading import Thread
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,re
from common.helper import Helper
class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "康乐无忧两全保险（B款）产品组合"
    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000", "300000", "400000", "500000"],
                # 保障期限
                "expire": ["70岁", "80岁", "90岁"],
                # 交费间隔
                "interval": ["10", "15", "20"],
                # 交费类型
                "payType": ["年交"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(18, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000", "300000", "400000", "500000", "600000"],
                # 保障期限
                "expire": ["70岁", "80岁", "90岁"],
                # 交费间隔
                "interval": ["10", "15", "20"],
                # 交费类型
                "payType": ["年交"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000", "300000", "400000"],
                # 保障期限
                "expire": ["70岁", "80岁", "90岁"],
                # 交费间隔
                "interval": ["10", "15", "20"],
                # 交费类型
                "payType": ["年交"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000", "300000"],
                # 保障期限
                "expire": ["70岁", "80岁", "90岁"],
                # 交费间隔
                "interval": ["10", "15", "20"],
                # 交费类型
                "payType": ["年交"]
            }

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["money"], plan[k]["expire"],
                             plan[k]["interval"], plan[k]["payType"]):
                data = Helper.formatProductInfo(plan[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def reqeustJson(self,dt=None,mysql=None):
        data = "callCount=1\n" \
               "page=/sia4/webflow/KLWYBPolicyLongEntry-flow.jspf?execution=e1s1\n" \
               "httpSessionId=\n" \
               "scriptSessionId=3FF01CD1A010A127433209F64AB8ECEA421\n" \
               "c0-scriptName=LongPolicyRateManager\n" \
               "c0-methodName=quotePolicyKLWY\n" \
               "c0-id=0\n" \
               "c0-e1=string:\n" \
               "c0-e2=string:\n" \
               "c0-e3=string:\n" \
               "c0-e4=string:\n" \
               "c0-e5=string:\n" \
               "c0-e6=string:\n" \
               "c0-e7=string:\n" \
               "c0-e8=string:\n" \
               "c0-e9=string:null\n" \
               "c0-e10=string:6473c1da550df5efd8eef74c1d5941d3\n" \
               "c0-e11=string:"+dt["gender"]+"\n" \
               "c0-e12=string:"+str(2020-int(dt["year"]))+"-01-01\n" \
               "c0-e13=string:"+dt["money"]+"\n" \
               "c0-e14=string:%E6%89%8B%E5%8A%A8%E5%BD%95%E5%85%A5\n" \
               "c0-e15=string:"+dt["expire"].replace("岁","")+"\n" \
               "c0-e16=string:"+dt["interval"]+"\n" \
               "c0-e17=string:\n" \
               "c0-e18=string:e1s1\n" \
               "c0-e19=string:\n" \
               "c0-e20=string:\n" \
               "c0-e21=string:"+dt["year"]+"\n" \
               "c0-e22=string:Self\n" \
               "c0-param0=Object_Object:{_action:reference:c0-e1, _method:reference:c0-e2, _view:reference:c0-e3, _editing:reference:c0-e4, _advSearch:reference:c0-e5, _ignoreBind:reference:c0-e6, _coid:reference:c0-e7, __oid:reference:c0-e8, _stoken:reference:c0-e9, _windowContextId:reference:c0-e10, roleMap%5B'Insured'%5D%5B0%5D.allPropertyActuals%5B'gender'%5D.enumNameValue:reference:c0-e11, roleMap%5B'Insured'%5D%5B0%5D.allPropertyActuals%5B'birthDate'%5D.dateValue:reference:c0-e12, insuredAmount:reference:c0-e13, insuredAmountInput:reference:c0-e14, allPropertyActuals%5B'benefitPeriod'%5D.intValue:reference:c0-e15, allPropertyActuals%5B'paymentDuration'%5D.intValue:reference:c0-e16, _eventId:reference:c0-e17, _flowExecutionKey:reference:c0-e18, quoteFlag:reference:c0-e19, Flag:reference:c0-e20, insuredAge:reference:c0-e21, roleMap%5B'Insured'%5D%5B0%5D.allPropertyActuals%5B'relatedToRoleCode'%5D.enumNameValue:reference:c0-e22}\n" \
               "batchId=159"
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=data)
        if r.status_code == 200 and "grossPremium" in r.text:
            grossPremium = re.search(r'grossPremium:(.*?),',r.text).group(1)
            coverage_premium = re.search(r'\'coverage_premium\':(.*)}',r.text).group(1)
            total_price = Helper.decimalParse( float(grossPremium) + float(coverage_premium) )
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":total_price
            }
            mysql.updatePrice( data )
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask( data )
            print("\n/*更新产品价格失败:%d*/"%dt["id"])

    def main(self, mysql):
        while True:
            # 随机领取一条数据
            dt = mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)
            self.reqeustJson(dt, mysql)

    # 多线程
    def startProcess(self):

        for i in range(5):

            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))

            t.start()
